<template>
    <div class="login-form">
        <div class="title-box"><h1>登录</h1></div>
        <el-form ref="loginFormRef" :model="loginForm" :rules="rules"  class="input-box">
            <el-form-item prop="username">
                <el-input v-model="loginForm.username" type="text" placeholder="用户名" clearable></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="密码" clearable show-password>
                    <template #append>
                        <span @click="switchToRetrieve">忘记密码?</span>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <div class="button-box">
                    <el-button type="primary" @click="login(loginFormRef)">登录</el-button>
                    <p @click="switchToRegister">没有账号?去注册</p>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
    import { ref,reactive, unref,getCurrentInstance } from 'vue';
    import { useRouter } from 'vue-router';
    import axios from 'axios';
    import { ElMessage } from 'element-plus';
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    const loginFormRef = ref();
    const loginForm = reactive({
        username:ref(''),
        password:ref(''),
    });

    const switchToRegister = () => {
        router.push('/user/register');
    };

    const switchToRetrieve = () => {
        router.push('/user/Retrieve');
    };

    const rules = reactive({
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3,max:12, message: '用户名长度为3-12个字符', trigger: ['change','blur']}
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max:16,message: '密码长度为6-16个字符', trigger: ['change','blur'] },
            { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/, message: '密码必须包含字母和数字', trigger: ['change','blur'] }
        ]
    });

    const login = async () => {
        const form=unref(loginFormRef);
        if (!form) {
            ElMessage.error('表单不存在');
            return;
        }
        await form.validate(async (valid) => {
            if (valid) {
                try {
                    await proxy.$http.post('/Login/', {
                        user_name: loginForm.username,
                        pass_word: loginForm.password,
                    }).then((res)=>{
                        if (res.data.status === 'success') {
                            localStorage.setItem('userToken', res.data.token);
                            localStorage.setItem('account',loginForm.username)
                            console.log(res.data.token);
                            //路由跳转到主页
                            router.push('/'); 
                            ElMessage.success('登录成功');
                        } else if (res.data.status === 'error') {
                            ElMessage.error(res.data.message);
                        }
                    })
                } catch (error) {
                    ElMessage.error('请求失败，请稍后重试');
                }
            } else {
                ElMessage.error('请检查输入');
            }
        });
    };
</script>

<style scoped>
    .login-form {
        height: 100%;
        width: 50%;
        position:absolute;
        top: 0;
        left: 50%;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .title-box {
        margin-top: 25%;
        margin-bottom: 10%;
    }
    .title-box h1 {
        text-align: center;
        align-items: center;
        letter-spacing: 5px;
        color: white;
        text-shadow: 4px 4px 3px rgba(0, 0, 0, .1);
        font-size: 25px;
    }
    .el-form{
        width: 60%;
    }
    .input-box span:hover{
        cursor: pointer;
    }
    .button-box {
        display: flex;
        margin: auto;
    }
    .el-input {
        height: 100%;
        border: 1px solid #b0cfe9;
    }
    button{
        width:100px;
        height: 30px;
        line-height: 30px;
        border: none;
        border-radius: 4px;
        background-color: #69b3f0;
        color: white;
        margin-right: 5px;
    }
    .button-box p{
        color: white;
        font-size: 16px;
    }
    .button-box p:hover{
        cursor: pointer;
    }
</style>